package by.scsbsu.database.dao;

import by.scsbsu.database.bean.MessageAttach;
import by.scsbsu.database.tools.DbConnectionPool;

public class MessageAttachDAO extends AbstractDAO {

	public static final String SQL_MESSAGE_ATTACH_CREATE_MESSAGE = "INSERT INTO message_attach ( id_message , file ) VALUES ( ? , ? );";
	public static final String SQL_MESSAGE_ATTACH_GET_ID_CREATE_MESSAGE = "SELECT id FROM message_attach WHERE ( ( id_message = ? ) AND ( file = ? ) );";
	public static final String SQL_MESSAGE_ATTACH_DELETE_MESSAGE_BY_ID = "DELETE FROM message_attach WHERE ( id = ? );";
	public static final String SQL_MESSAGE_ATTACH_GET_FILE_BY_ID = "SELECT file FROM message_attach WHERE ( id = ? );";
	
	
	public MessageAttach createMessageAttach(MessageAttach messageAttach){
		try {
			connection = DbConnectionPool.getConnection();
			
			statement = connection.prepareStatement(SQL_MESSAGE_ATTACH_CREATE_MESSAGE);
			statement.setInt(1, messageAttach.getIdMessage());
			statement.setString(2, messageAttach.getFile());
			statement.executeUpdate();
			
			statement = connection.prepareStatement(SQL_MESSAGE_ATTACH_GET_ID_CREATE_MESSAGE);
			statement.setInt(1, messageAttach.getIdMessage());
			statement.setString(2, messageAttach.getFile());
			
			resultSet = statement.executeQuery();
			if(resultSet.next()){
				messageAttach.setId(resultSet.getInt("id"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
		return messageAttach;
	}
	
	public void deleteMessageAttachById(int id){
		try {
			connection = DbConnectionPool.getConnection();
			
			statement = connection.prepareStatement(SQL_MESSAGE_ATTACH_DELETE_MESSAGE_BY_ID);
			statement.setInt(1, id);
			statement.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}
	
	public String getFileById(int id){
		String file = new String();
		try {
			connection = DbConnectionPool.getConnection();
			
			statement = connection.prepareStatement(SQL_MESSAGE_ATTACH_GET_FILE_BY_ID);
			statement.setInt(1, id);
			
			resultSet = statement.executeQuery();
			if(resultSet.next()){
				file = resultSet.getString("file");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
		return file;
	}
}
